//
//  N2STAppDelegate.m
//  N2ST
//
//  Created by Eduardo Oliveros on 30/12/08.
//  Copyright Eduardo Oliveros 2008. All rights reserved.
//

#import "N2STAppDelegate.h"
#import "RootViewController.h"
#import "JSON.h"

@interface UIAlertView (extended)
- (UITextField *) textFieldAtIndex: (int) index;
- (void) addTextFieldWithValue: (NSString *) value label: (NSString *) label;
@end

@implementation TaskNode
@synthesize taskName;
@synthesize taskDuration;
@synthesize taskID;
@end


@implementation ProjectNode
@synthesize projectName;
@synthesize projectID;
@synthesize tasks;
@end

@implementation N2STAppDelegate

@synthesize window;
@synthesize navigationController;
@synthesize keysec;
@synthesize loginDict;
@synthesize projects;

- (id)init {
	if (self = [super init]) {
		// 
	}
	return self;
}

-(NSString*) getDataFileName{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	
	return [documentsDirectory stringByAppendingPathComponent:@"data"];
}

- (void)applicationDidFinishLaunching:(UIApplication *)application {
	//show the main window
	[self showWindow];
	
	//XXX - only for testing purposes will be removed later
#define REMOVE_FILE1
#ifdef REMOVE_FILE
	NSFileManager  *NSFm;
	NSFm = [NSFileManager defaultManager];
	[NSFm removeFileAtPath: [self getDataFileName] handler: nil];
#endif
	
	//Load login and password or ask for it
	//try to load the information from a file
	NSLog(@"data file=%@", [self getDataFileName]);
	[self setLoginDict: [NSMutableDictionary dictionaryWithContentsOfFile:[self getDataFileName]]];
	
	//if is not possible ask the information to the user
	if(!loginDict){
		//Create an empty loginDict
		[self setLoginDict: [NSMutableDictionary dictionaryWithCapacity:2]];
		
		//Ask for the information to the user
		UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Enter your Nozbe account" 
														message:@"Open a free account in nozbe.com" 
													   delegate:self 
											  cancelButtonTitle:@"Go Nozbe..." 
											  otherButtonTitles:@"OK", nil ];
		[alert addTextFieldWithValue:@"" label:@"login"];
		[alert addTextFieldWithValue:@"" label:@"password"];
		
		//Login Field
		UITextField* tf = [alert textFieldAtIndex:0];
		tf.clearButtonMode = UITextFieldViewModeWhileEditing;
		tf.keyboardType = UIKeyboardTypeAlphabet;
		tf.keyboardAppearance = UIKeyboardAppearanceAlert;
		tf.autocapitalizationType = UITextAutocapitalizationTypeNone;
		tf.autocorrectionType = UITextAutocorrectionTypeNo;
		
		//Password Field
		tf = [alert textFieldAtIndex:1];
		tf.clearButtonMode = UITextFieldViewModeNever;
		tf.keyboardType = UIKeyboardTypeAlphabet;
		tf.keyboardAppearance = UIKeyboardAppearanceAlert;
		tf.autocapitalizationType = UITextAutocapitalizationTypeNone;
		tf.autocorrectionType = UITextAutocorrectionTypeNo;
		tf.secureTextEntry = YES;
		
		[alert show];
	} else {
		[self syncNozbe];
	}
}

//retrieves the information from the user (login and password)
// XXX - check if login/password are valid
-(void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger) buttonIndex{
	if(buttonIndex == 0){
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.nozbe.com/gtd/show/site-course1/a-3DE643AF"]];
	}
	if(buttonIndex == 1){
		//stores the values
		[loginDict setValue:[[alertView textFieldAtIndex:0] text] forKey:@"login"];
		[loginDict setValue:[[alertView textFieldAtIndex:1] text] forKey:@"password"];		
	}
	
	//store the information in a local file (data)
	[loginDict writeToFile:[self getDataFileName] atomically:YES];
	
	//get Nozbe account information (projects and tasks)
	[self syncNozbe];
	
}

//Synchronize the information with the Nozbe Account
-(void)syncNozbe{
	progressAlert = [[ProgressAlert alloc] initWithTitle:@"Sync Nozbe" message:@"reading Projects" delegate:self];

	//execute the synchronization process in a thread
	NSThread* SyncThread=[[NSThread alloc]initWithTarget:self 
												selector:@selector(performSyncNozbe:) 
												  object:nil]; 
	[SyncThread start];
	
	[progressAlert show];
}

//set the new text in the UIAlertView (called from the thread)
-(void) redrawAlert:(NSString*)message {
	[progressAlert setMessage:message];
}

//Load the data from the Nozbe server (JSON API).
-(void)performSyncNozbe:(id)param{
	//Load the Project
	//get the user key
	//Form the URL
	NSString* URLstr = [NSString stringWithFormat:@"http://www.nozbe.com/api/login/email-%@/password-%@",
						[loginDict valueForKey:@"login"],
						[loginDict valueForKey:@"password"]];
	
	
	//Get the secret key
	id response = [self objectWithUrl:[NSURL URLWithString:URLstr]];
	NSDictionary *keysecDict = (NSDictionary *)response;
	keysec = [keysecDict valueForKey:@"key"];
	NSLog(@"key=%@", keysec); //REML
	
	//Get the projects
	URLstr = [NSString stringWithFormat:@"http://www.nozbe.com/api/projects/key-%@", keysec];
	response = [self objectWithUrl:[NSURL URLWithString:URLstr]];
	NSArray *projectsReq = (NSArray *)response;
	if(projectsReq == nil){
		//Borra el fichero de data
		NSFileManager  *NSFm;
		NSFm = [NSFileManager defaultManager];
		[NSFm removeFileAtPath: [self getDataFileName] handler: nil];

		//ends application
		[[UIApplication sharedApplication] endIgnoringInteractionEvents];
	}
	
	//Build the Projects Array
	projects = [NSMutableArray arrayWithCapacity:projectsReq.count];
	
	int i;
	for(i=0; i<projectsReq.count; i++){
		//Obtiene el objeto con la información del proyecto
		NSDictionary *project = (NSDictionary*) [projectsReq objectAtIndex:i];

		//Crea un ProjectNode y lo añade al array
		ProjectNode* projectNode = [[ProjectNode alloc]init];
		[projectNode setProjectName: (NSString*)[project valueForKey:@"name"]];
		[projectNode setProjectID: (NSString*)[project valueForKey:@"id"]];
		//Add the projectNode to the array of projects
		[projects addObject:projectNode];
		NSLog(@"project=%@",(NSString*)[project valueForKey:@"name"]); //REML
	}
	
	//Get the tasks
	//For each project
	for(i=0; i<projectsReq.count; i++){
		ProjectNode* projectNode=[projects objectAtIndex:i];
		//update alarm window
		NSString* message = [NSString stringWithFormat:@"Tasks of project: %@", [projectNode projectName]];
		[self performSelectorOnMainThread:@selector(redrawAlert:) withObject:message waitUntilDone:NO];
		
		URLstr = [NSString stringWithFormat:@"http://www.nozbe.com/api/actions/what-project/id-%@/key-%@", 
			  projectNode.projectID,
			  keysec];
		response = [self objectWithUrl:[NSURL URLWithString:URLstr]];
		NSArray *tasksReq = (NSArray *)response;
		
		//For each Task, create a node and populate the array
		[projectNode setTasks: [NSMutableArray arrayWithCapacity:tasksReq.count]];
		
		int j;
		for(j=0; j<tasksReq.count;j++){
			//obtain the task array from the JSON request
			NSDictionary* task = [tasksReq objectAtIndex:j];
			if( [[task valueForKey:@"done"] compare:@"0"] == NSOrderedSame ){
				//create the node for this Task
				TaskNode* taskNode = [[TaskNode alloc]init];
				[taskNode setTaskName:[task valueForKey:@"name"]];
				[taskNode setTaskDuration:[NSString stringWithFormat:@"%@m",[task valueForKey:@"time"]]];
				[taskNode setTaskID:[task valueForKey:@"id"]];
				//add the node to the array
				[[projectNode tasks] addObject:taskNode];
			}
		}

	};
	
	NSLog(@"end load of data...");
	[progressAlert dismissWithClickedButtonIndex:-1 animated:YES];
	[progressAlert release];
	
	//reload the table
	NSLog(@"reload Table...");
	UITableView* table = (UITableView*)[window viewWithTag:1];
	[table  reloadData];
	
	exit;
}

-(void) completeAction:(NSInteger)nTask ofProject:(NSInteger)nProject{
	TaskNode* taskNode = [[[projects objectAtIndex:nProject] tasks] objectAtIndex:nTask];
	NSString* URLstr = [NSString stringWithFormat:@"http://www.nozbe.com/api/check/ids-%@/key-%@", 
			  taskNode.taskID,
			  keysec];
	/*id response =*/ [self objectWithUrl:[NSURL URLWithString:URLstr]];
	
}

//Show main window and start the application
-(void)showWindow{
	// Configure and show the window
	[window addSubview:[navigationController view]];
	[window makeKeyAndVisible];
}


- (void)applicationWillTerminate:(UIApplication *)application {
	// Save data if appropriate
}


- (void)dealloc {
	//XXX- elimina el array de proyectos
	NSLog(@"AppDel: dealloc !!!!");
	[navigationController release];
	[window release];
	[super dealloc];
}

- (id) objectWithUrl:(NSURL *)url
{
	SBJSON *jsonParser = [SBJSON new];
	NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:NULL];
	
	//NSLog(@"jsonString=%@", jsonString);
	
	// Parse the JSON into an Object
	return [jsonParser objectWithString:jsonString error:NULL];
}


@end
